package com.ray.monitor.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ray.api.service.UcenterApiService;
import com.ray.auth.system.table.entity.Button;
import com.ray.monitor.service.HostService;
import com.ray.monitor.table.vo.HostBO;
import com.ray.monitor.util.DataGridUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.web.controller.WebController;

/**
 * Created by zxg on 15/12/3.
 * 16:39
 */
@Controller
@RequestMapping("/monitor/dubbo/host")
public class HostController extends WebController{

    @Autowired
    private HostService hostService;
    @Autowired
	UcenterApiService ucenterApiService;
    
    @RequestMapping(value = "view")
  	@RequiresPermissions("monitor:dubbo:host:view")
  	public ModelAndView view(String menuId, HttpServletRequest request, HttpServletResponse respose,
  			ModelAndView modelAndView) {
  		LoginUser user = getLoginUser();
  		// 查询页面拥有的资源
  		Result<Map<String, List<Button>>> buttonsResult = ucenterApiService.queryUserButtonsWithMenu(user, menuId);
  		if (buttonsResult.codeSuccess()) {
  			modelAndView.addObject("buttons", buttonsResult.getData());
  		}
  		modelAndView.setViewName("monitor/dubbo/host/view");
  		return modelAndView;
  	}

  	
  	/**
  	 * 查询页面
  	 */
  	@SuppressWarnings("unchecked")
  	@RequestMapping(value = "query")
  	@RequiresPermissions("monitor:dubbo:host:query")
  	@ResponseBody
  	public ResponseEntity<Map<String, Object>> query(String hostIp,HttpServletRequest request,HttpServletResponse respose) {
  		  PageDto<HostBO> page = this.createJQPage(request);
  		  Map<String,HostBO> hostMap = hostService.getHostBOMap();
            List<HostBO> appList = new ArrayList<>();
            for (Map.Entry<String, HostBO> hostBOEntry : hostMap.entrySet()) {
               if(StrUtil.isBlank(hostIp) ||StrUtil.equals(hostIp, hostBOEntry.getKey()) ){
                   appList.add(hostBOEntry.getValue());
               }
            }
           page.setRecords(appList);
           page.setTotal(appList.size());
  		return doSuccess(DataGridUtil.dataConvert(page));

  	}
 

}
